package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.TcClassMember;
import com.zhentao.service.TcClassMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("tea/classMember")
public class ClassMemberController {

    @Autowired
    TcClassMemberService classMemberService;

    /**
     * 获取全部班级成员关系
     */
    @GetMapping("list")
    public List<TcClassMember> list(){
        return classMemberService.list();
    }

    /**
     * 根据ID获取班级成员关系详情
     */
    @GetMapping("get/{id}")
    public TcClassMember getById(@PathVariable Integer id){
        return classMemberService.getById(id);
    }

    /**
     * 添加班级成员
     */
    @PostMapping("add")
    public Map<String, Object> add(@RequestBody TcClassMember classMember){
        Map<String, Object> result = new HashMap<>();
        try {
            classMember.setJoinTime(new Date());
            boolean success = classMemberService.save(classMember);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
            if (success) {
                result.put("data", classMember);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新班级成员信息
     */
    @PutMapping("update")
    public Map<String, Object> update(@RequestBody TcClassMember classMember){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = classMemberService.updateById(classMember);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            if (success) {
                result.put("data", classMember);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除班级成员
     */
    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = classMemberService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据班级ID获取成员列表
     */
    @GetMapping("classMembers/{classId}")
    public List<TcClassMember> getClassMembers(@PathVariable Integer classId){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 根据用户ID获取加入的班级
     */
    @GetMapping("userClasses/{userId}")
    public List<TcClassMember> getUserClasses(@PathVariable Integer userId){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 根据角色获取班级成员
     */
    @GetMapping("membersByRole/{classId}/{role}")
    public List<TcClassMember> getMembersByRole(@PathVariable Integer classId, @PathVariable String role){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.eq("role", role);
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 获取班级老师列表
     */
    @GetMapping("classTeachers/{classId}")
    public List<TcClassMember> getClassTeachers(@PathVariable Integer classId){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.eq("role", "老师");
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 获取班级学生列表
     */
    @GetMapping("classStudents/{classId}")
    public List<TcClassMember> getClassStudents(@PathVariable Integer classId){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.eq("role", "学生");
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 获取班级家长列表
     */
    @GetMapping("classParents/{classId}")
    public List<TcClassMember> getClassParents(@PathVariable Integer classId){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.eq("role", "家长");
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 获取班级家委列表
     */
    @GetMapping("classCommittee/{classId}")
    public List<TcClassMember> getClassCommittee(@PathVariable Integer classId){
        QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.eq("role", "家委");
        queryWrapper.orderByDesc("join_time");
        return classMemberService.list(queryWrapper);
    }

    /**
     * 检查用户是否在班级中
     */
    @GetMapping("checkMember/{userId}/{classId}")
    public Map<String, Object> checkMember(@PathVariable Integer userId, @PathVariable Integer classId){
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("class_id", classId);
            TcClassMember member = classMemberService.getOne(queryWrapper);
            
            result.put("isMember", member != null);
            result.put("member", member);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "检查失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 用户加入班级
     */
    @PostMapping("joinClass")
    public Map<String, Object> joinClass(@RequestParam Integer userId, @RequestParam Integer classId, @RequestParam String role){
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查是否已经在班级中
            QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("class_id", classId);
            TcClassMember existingMember = classMemberService.getOne(queryWrapper);
            
            if (existingMember != null) {
                result.put("success", false);
                result.put("message", "用户已在该班级中");
                return result;
            }
            
            TcClassMember classMember = new TcClassMember();
            classMember.setUserId(userId);
            classMember.setClassId(classId);
            classMember.setRole(role);
            classMember.setJoinTime(new Date());
            
            boolean success = classMemberService.save(classMember);
            result.put("success", success);
            result.put("message", success ? "加入班级成功" : "加入班级失败");
            if (success) {
                result.put("data", classMember);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "加入班级失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 用户退出班级
     */
    @DeleteMapping("leaveClass/{userId}/{classId}")
    public Map<String, Object> leaveClass(@PathVariable Integer userId, @PathVariable Integer classId){
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<TcClassMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("class_id", classId);
            boolean success = classMemberService.remove(queryWrapper);
            result.put("success", success);
            result.put("message", success ? "退出班级成功" : "退出班级失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "退出班级失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除班级成员
     */
    @DeleteMapping("batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> ids){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = classMemberService.removeByIds(ids);
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败：" + e.getMessage());
        }
        return result;
    }
}
